<script lang="ts" setup>
import { ref, watch, computed, onMounted, nextTick } from "vue";
import { role } from "../index";
import * as markedLib from "marked";
const { marked } = markedLib;
import hljs from "highlight.js";
import "highlight.js/styles/github.css";
import mermaid from "mermaid";

// 更新mermaid初始化配置，支持更多高级特性
mermaid.initialize({
  startOnLoad: false,
  theme: "default",
  securityLevel: 'loose', // 允许更多功能
  fontFamily: 'sans-serif',
  sequence: {
    showSequenceNumbers: true, // 支持autonumber
    actorMargin: 80, // 增加角色之间的间距
    boxMargin: 10, // box边距
    mirrorActors: false,
    bottomMarginAdj: 10, // 底部边距调整
    useMaxWidth: true,
    width: 150, // 角色框宽度
  },
  flowchart: {
    useMaxWidth: true,
    htmlLabels: true,
    curve: 'basis'
  },
  er: {
    useMaxWidth: true
  }
});

// 配置 marked
// @ts-ignore - 忽略类型检查，因为marked类型定义与实际使用有差异
marked.setOptions({
  renderer: new marked.Renderer(),
  // @ts-ignore
  highlight: (code, lang) => {
    const language = hljs.getLanguage(lang) ? lang : "plaintext";
    return hljs.highlight(code, { language }).value;
  },
  langPrefix: "hljs language-",
});

const props = withDefaults(
  defineProps<{
    selectId: any;
    userDatabase: any;
  }>(),
  {
    selectId: 0,
    userDatabase: [],
  }
);

const clbRole = ref(props.selectId);
const loading = ref(false);
const isFold = ref(true);
const topFold = ref(false);
const isMermaid = ref(false);

const editorPromptValue = ref<any>([]);
const editorValue = ref<any>();
const markdownContent = ref<string>("");
const hasBase64Image = ref(false);
const base64ImageSrc = ref("");
const explanationText = ref("");
const childData = ref(props.userDatabase)

// 存储已处理过的结论，key是结论答案内容，value包含解析后的信息
const processedConclusions = ref<Map<string, any>>(new Map());

// 滚动容器引用
const scrollContainer: any = ref(null);

// 保存所有结论内容的数组，用于结论模式下的展示
const allConclusions = ref<any[]>([]);

const defaultProps = {
    children: 'children',
    label: 'label',
}

// 添加结论布局模式变量
const conclusionLayout = ref('compact'); // 'compact' 或 'expanded'

// 切换结论布局模式
const toggleConclusionLayout = () => {
  conclusionLayout.value = conclusionLayout.value === 'compact' ? 'expanded' : 'compact';
};

// 修改获取当前会话中的所有结论的函数，增强无图片情况下的explain提取
const getConclusionsInCurrentSession = () => {
  if (!editorPromptValue.value || editorPromptValue.value.length === 0) {
    return allConclusions.value;
  }

  const currentSession =
    editorPromptValue.value[editorPromptValue.value.length - 1];
  const newConclusions = currentSession
    .filter((item: any) => item.id == 4) // 只获取结论（id=4）
    .map((conclusion: any) => {
      // 检查是否已处理过这个结论
      if (!processedConclusions.value.has(conclusion.answer)) {
        // 尝试解析JSON内容
        let extractedExplanation = "";
        let renderedMarkdown = "";
        let hasBase64 = false;

        try {
          const jsonObj = JSON.parse(conclusion.answer || "");

          // 检查是否有explain字段
          if (jsonObj && typeof jsonObj === "object" && jsonObj.explain) {
            extractedExplanation = jsonObj.explain;
            // 无论是否有base64，都能提取到explain内容
          }
        } catch (e) {
          // 不是有效的JSON，直接使用原始内容
        }

        // 检查是否包含base64图片
        hasBase64 = checkForBase64Image(conclusion.answer || "");

        // 设置要渲染的Markdown内容
        if (hasBase64) {
          // 有base64图片，使用从图片中提取的说明
          renderedMarkdown = processMarkdown(explanationText.value || "图表分析结果");
        } else if (extractedExplanation) {
          // 无图片但有提取到explain内容
          renderedMarkdown = processMarkdown(extractedExplanation);
        } else {
          // 无图片也无explain，使用原始内容
          renderedMarkdown = processMarkdown(conclusion.answer || "");
        }

        // 创建结论对象，添加时间戳和唯一ID
        const conclusionItem = {
          id: Date.now() + Math.random().toString(36).substring(2, 9), // 生成唯一ID
          hasBase64,
          base64Src: hasBase64 ? base64ImageSrc.value : "",
          explanation: extractedExplanation || explanationText.value,
          markdown: renderedMarkdown,
          rawAnswer: conclusion.answer,
          timestamp: Date.now()
        };

        // 存储处理结果
        processedConclusions.value.set(conclusion.answer, conclusionItem);

        // 添加到所有结论数组中
        allConclusions.value.push(conclusionItem);
      }

      // 返回处理结果
      return processedConclusions.value.get(conclusion.answer);
    });

  // 对结论按时间戳排序
  allConclusions.value.sort((a, b) => a.timestamp - b.timestamp);

  return allConclusions.value;
};

// 修改checkForBase64Image函数，确保只有有效的base64图片才返回true
const checkForBase64Image = (content: string): boolean => {
  try {
    // 尝试解析为JSON
    const jsonObj = JSON.parse(content);

    // 检查是否存在base64字段
    if (jsonObj && typeof jsonObj === "object") {
      // 直接检查base64字段
      if (
        jsonObj.base64 &&
        typeof jsonObj.base64 === "string" &&
        jsonObj.base64.length > 100 && // 确保base64字符串不为空且长度合理
        (jsonObj.base64.startsWith("data:image") ||
          jsonObj.base64.startsWith("iVBOR") ||
          jsonObj.base64.startsWith("/9j/"))
      ) {
        // 确保base64字符串格式正确
        if (jsonObj.base64.startsWith("data:image")) {
          base64ImageSrc.value = jsonObj.base64;
        } else if (
          jsonObj.base64.startsWith("iVBOR") ||
          jsonObj.base64.startsWith("/9j/")
        ) {
          // 添加正确的前缀
          base64ImageSrc.value = `data:image/png;base64,${jsonObj.base64}`;
        }

        // 提取explain字段作为Markdown内容
        if (jsonObj.explain && typeof jsonObj.explain === "string") {
          explanationText.value = jsonObj.explain;
        } else {
          // 如果没有explain字段，尝试查找其他可能的说明字段
          const possibleExplanationFields = [
            "description",
            "text",
            "content",
            "explanation",
          ];
          for (const field of possibleExplanationFields) {
            if (jsonObj[field] && typeof jsonObj[field] === "string") {
              explanationText.value = jsonObj[field];
              break;
            }
          }
        }

        return true;
      }

      // 递归检查对象的所有字段
      for (const key in jsonObj) {
        const value = jsonObj[key];

        // 检查是否是可能的base64字符串字段
        if (typeof value === "string" && value.length > 100) {
          // 检查是否是base64图片数据
          if (
            (key.toLowerCase().includes("base64") ||
              key.toLowerCase().includes("image")) &&
            (value.startsWith("data:image") ||
              value.startsWith("iVBOR") ||
              value.startsWith("/9j/"))
          ) {
            if (value.startsWith("data:image")) {
              base64ImageSrc.value = value;
            } else {
              // 添加正确的前缀
              base64ImageSrc.value = `data:image/png;base64,${value}`;
            }

            // 尝试查找相关的explain字段
            if (jsonObj.explain && typeof jsonObj.explain === "string") {
              explanationText.value = jsonObj.explain;
            } else {
              // 如果没有explain字段，尝试查找其他可能的说明字段
              const possibleExplanationFields = [
                "description",
                "text",
                "content",
                "explanation",
              ];
              for (const field of possibleExplanationFields) {
                if (jsonObj[field] && typeof jsonObj[field] === "string") {
                  explanationText.value = jsonObj[field];
                  break;
                }
              }
            }

            return true;
          }
        } else if (typeof value === "object" && value !== null) {
          // 递归检查嵌套对象
          const nestedString = JSON.stringify(value);
          if (checkForBase64Image(nestedString)) {
            return true;
          }
        }
      }

      // 如果没有找到有效的base64图片，但找到了explain字段，也提取出来
      if (jsonObj.explain && typeof jsonObj.explain === "string") {
        explanationText.value = jsonObj.explain;
        // 返回false表示没有图片，但有explain内容
      }
    }
  } catch (e) {
    // 不是有效的JSON，直接检查字符串
    // 检查是否包含完整的base64图片数据URI
    const base64DataUriRegex = /data:image\/[^;]+;base64,[a-zA-Z0-9+/]+=*/g;
    const matches = content.match(base64DataUriRegex);

    if (matches && matches.length > 0 && matches[0].length > 100) {
      base64ImageSrc.value = matches[0];
      // 尝试提取图片之外的文本作为说明
      const textParts = content.split(base64DataUriRegex);
      if (textParts.length > 0) {
        explanationText.value = textParts.join(" ").trim();
      }
      return true;
    }

    // 检查是否包含原始base64编码的图片数据（没有data URI前缀）
    const rawBase64Regex = /"[a-zA-Z0-9+/]{100,}={0,2}"/;
    const rawMatches = content.match(rawBase64Regex);

    if (rawMatches && rawMatches.length > 0) {
      // 去除引号
      let base64Data = rawMatches[0].replace(/"/g, "");

      // 判断可能的图片类型并添加适当的前缀
      if (base64Data.startsWith("iVBOR")) {
        // PNG图片
        base64ImageSrc.value = `data:image/png;base64,${base64Data}`;
      } else if (base64Data.startsWith("/9j/")) {
        // JPEG图片
        base64ImageSrc.value = `data:image/jpeg;base64,${base64Data}`;
      } else {
        // 默认为PNG
        base64ImageSrc.value = `data:image/png;base64,${base64Data}`;
      }

      // 尝试从剩余内容中提取说明文本
      const textParts = content.split(rawBase64Regex);
      if (textParts.length > 0) {
        explanationText.value = textParts.join(" ").trim();
      }

      return true;
    }

    // 尝试提取可能的explain内容
    try {
      const jsonMatch = content.match(/"explain"\s*:\s*"([^"]*)"/);
      if (jsonMatch && jsonMatch[1]) {
        explanationText.value = jsonMatch[1];
      }
    } catch (err) {
      // 忽略解析错误
    }
  }

  return false;
};

const changeRole = (item: any) => {
  clbRole.value = item.id;
  loading.value = true;

  // 如果是结论角色(id=4)，使用多结论渲染
  if (item.id == 4) {
    // 多结论渲染会在模板中通过getConclusionsInCurrentSession()处理
  } else {
    // 非结论角色的处理逻辑
    const answer = editorPromptValue.value[
      editorPromptValue.value.length - 1
    ]?.filter((el: any) => el.id == item.id)[0]?.answer;

    // 将答案转换为 Markdown
    markdownContent.value = answer || "";

    // 检查是否包含base64图片
    hasBase64Image.value = checkForBase64Image(markdownContent.value);

    if (hasBase64Image.value) {
      // 如果有base64图片，使用提取的explanationText渲染
      editorValue.value = processMarkdown(explanationText.value || "");
    } else {
      // 否则使用原内容渲染
      editorValue.value = processMarkdown(markdownContent.value);
    }
  }

  setTimeout(() => {
    loading.value = false;
    // 滚动到顶部以便用户查看完整内容
    if (scrollContainer.value) {
      scrollContainer.value.scrollTop = 0;
    }
  }, 500);
};

const addHighlight = (data: any[], str: string) => {
  if (data.length === 0 || !str) return data;

  data.forEach((item: any) => {
    if (str.includes(item.label + '：')||str.includes(item.label + ':')) {
        item.highlight = true;
        if (item.children) {
            item.children.forEach((child: any) => {
                if (str.includes(child.name)) {
                    child.highlight = true;
                }
            });
        }
    }
  });
  return data;
};

const renderContent = (h, { node, data, store }) => {
    let style = {};
    let label = node.label;
    if (data.highlight) {
        style = { color: '#1a2ad1' };
    } else {
        style = { color : '#000' };
    }
    return h('span', {style}, label);
}

// 修改mermaid渲染函数，添加防抖功能
let mermaidRenderTimer: ReturnType<typeof setTimeout> | null = null;

const renderMermaidDiagrams = () => {
  // 清除之前的定时器，防止重复渲染
  if (mermaidRenderTimer) {
    clearTimeout(mermaidRenderTimer);
  }

  // 设置新的定时器，延迟渲染
  mermaidRenderTimer = setTimeout(() => {
    try {
      // 查找所有包含"mermaid"类的元素
      const elements = document.querySelectorAll('.mermaid');
      if (elements.length > 0) {
        console.log(`找到${elements.length}个mermaid元素`);

        elements.forEach((el, index) => {
          try {
            // 获取内容并清理
            let content = el.innerHTML;

            // 清理HTML标签
            if (content.includes('<') || content.includes('>')) {
              content = content
                .replace(/<\/?pre>/g, '')
                .replace(/<\/?code>/g, '')
                .replace(/<\/?div[^>]*>/g, '')
                .replace(/<\/?p>/g, '')
                .replace(/<\/?span[^>]*>/g, '')
                .replace(/<\/?ul[^>]*>/g, '')
                .replace(/<\/?li[^>]*>/g, '')
                .replace(/<\/?a[^>]*>/g, '')
                .replace(/<[^>]*>/g, ''); // 移除所有其他HTML标签
            }

            // 更新元素内容
            el.innerHTML = content;
          } catch (e) {
            console.error("清理mermaid内容时出错:", e);
          }
        });

        // 使用mermaid的run方法渲染所有图表
        mermaid.run({
          nodes: Array.from(elements) as HTMLElement[]
        }).catch(e => {
          console.error("Mermaid渲染失败:", e);

          // 显示错误信息
          elements.forEach(el => {
            if (!el.querySelector('svg')) {
              el.innerHTML = `<div class="mermaid-error">
                <p>图表渲染失败</p>
                <pre>${e.message || '未知错误'}</pre>
              </div>`;
            }
          });
        });
      }
    } catch (e) {
      console.error("Mermaid处理错误:", e);
    }
  }, 300); // 延迟300ms渲染
};

// 修改processMarkdown函数，更严格地分离mermaid内容，并确保返回字符串
const processMarkdown = (content: string) => {
  if (!content) return "";

  try {
    // 检查是否包含mermaid代码块
    if (content.includes("```mermaid") ||
      content.includes("sequenceDiagram") ||
      content.includes("erDiagram") ||
      content.includes("flowchart") ||
      content.includes("graph ")) {

      // 标记包含mermaid内容
      isMermaid.value = true;

      // 处理完整的mermaid代码块
      let processedContent = content;

      // 先尝试提取完整的mermaid代码块
      const mermaidRegex = /```mermaid\s+([\s\S]*?)```/g;
      let match;
      let hasMermaidBlock = false;

      while ((match = mermaidRegex.exec(content)) !== null) {
        hasMermaidBlock = true;
        const mermaidCode = match[1].trim()
          .replace(/&lt;/g, '<')
          .replace(/&gt;/g, '>')
          .replace(/&amp;/g, '&');

        // 替换为特殊标记，稍后处理
        processedContent = processedContent.replace(
          match[0],
          `###MERMAID_BLOCK_${Date.now()}_${Math.random().toString(36).substring(2, 9)}###${mermaidCode}###MERMAID_BLOCK_END###`
        );
      }

      // 如果没有找到完整的mermaid代码块，但内容看起来像是mermaid图表
      if (!hasMermaidBlock &&
        (processedContent.includes('sequenceDiagram') ||
          processedContent.includes('erDiagram') ||
          processedContent.includes('flowchart') ||
          processedContent.includes('graph '))) {

        // 清理可能的HTML实体和标签
        let cleanCode = processedContent.trim()
          .replace(/&lt;/g, '<')
          .replace(/&gt;/g, '>')
          .replace(/&amp;/g, '&')
          .replace(/<\/?pre>/g, '')
          .replace(/<\/?code>/g, '')
          .replace(/<\/?div[^>]*>/g, '');

        // 整个内容作为mermaid处理
        processedContent = `###MERMAID_BLOCK_${Date.now()}_${Math.random().toString(36).substring(2, 9)}###${cleanCode}###MERMAID_BLOCK_END###`;
      }

      // 使用marked处理非mermaid部分
      const result = marked.parse(processedContent) as string;

      // 恢复mermaid块并包装在div中
      const finalResult = result.replace(
        /###MERMAID_BLOCK_[0-9a-z_]+###([\s\S]*?)###MERMAID_BLOCK_END###/g,
        '<div class="mermaid">$1</div>'
      );

      // 延迟渲染mermaid图表
      setTimeout(renderMermaidDiagrams, 100);

      return finalResult;
    }

    // 普通markdown处理
    return marked.parse(content) as string;
  } catch (error) {
    console.error("Markdown处理错误:", error);
    return content;
  }
};

// 处理图片加载错误
const handleImageError = (event: Event) => {
  if (event.target instanceof HTMLImageElement) {
    event.target.src = '../../assets/images/image-error.png'; // 可以替换为错误图片路径
    event.target.classList.add('image-error');
    event.target.classList.remove('base64-image');
  }
};

watch(
    () => props.userDatabase,
    (newVal) => {
        if (newVal && newVal.length > 0 && childData.value.length === 0) {
            childData.value = newVal
        }
    },{ deep:true }
);

watch(
  () => editorPromptValue.value,
  (newVal) => {
    if (!newVal || newVal.length === 0) return;

    try {
      const lastConversation = newVal[newVal.length - 1];
      const lastMessage = lastConversation[lastConversation.length - 1];

      clbRole.value = lastMessage?.id;

      // 结论数据只存储在answer字段中
      const rawContent = lastMessage?.answer || "";

      // 结论角色(id=4)使用多结论渲染功能
      if (lastMessage?.id == 4) {
        // 多结论渲染会在模板中通过getConclusionsInCurrentSession()处理
        // 但我们仍需解析最新的结论来更新hasBase64Image和其他相关变量
        hasBase64Image.value = checkForBase64Image(rawContent);
      } else {
        // 检查内容是否包含base64图片数据
        hasBase64Image.value = checkForBase64Image(rawContent);

        // 检测是否有mermaid图表
        if (
          rawContent &&
          (rawContent.includes("```mermaid") ||
            rawContent.includes("erDiagram"))
        ) {
          isMermaid.value = true;
          // 延迟渲染mermaid图表，确保DOM已更新
          setTimeout(renderMermaidDiagrams, 500);
        }

        if (props.userDatabase && props.userDatabase.length > 0) {
          addHighlight(childData.value, rawContent);
        }

        // 保存原始 Markdown 内容
        markdownContent.value = rawContent;

        // 转换为 HTML 并设置
        if (hasBase64Image.value) {
          editorValue.value = processMarkdown(
            explanationText.value || "分析结果"
          );
        } else {
          editorValue.value = processMarkdown(markdownContent.value);
        }
      }

      // 添加自动滚动
      scrollToBottom();
    } catch (error) {
      console.error("处理editorPromptValue时出错:", error);
    }
  },
  { deep: true, immediate: true }
);

// 修改watch函数，减少渲染触发
watch(
  () => markdownContent.value,
  (newVal, oldVal) => {
    if (newVal && newVal !== oldVal && isMermaid.value) {
      // 只有内容变化且包含mermaid时才触发渲染
      renderMermaidDiagrams();
    }
  }
);

// 修改editorValue的watch
watch(
  () => editorValue.value,
  (newVal, oldVal) => {
    if (newVal && newVal !== oldVal && isMermaid.value) {
      // 只有内容变化且包含mermaid时才触发渲染
      renderMermaidDiagrams();
    }
  }
);

// 在onMounted中添加初始渲染
onMounted(() => {
  // 初始渲染
  setTimeout(renderMermaidDiagrams, 500);
});

// 添加滚动到底部的函数
const scrollToBottom = () => {
  if (scrollContainer.value) {
    nextTick(() => {
      scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight;
    });
  }
};

defineExpose({
  topFold,
  editorPromptValue,
});
</script>
<template>
  <div class="card-container mt-8px">
    <div class="card-top flex items-center relative">
      <span v-for="item in role" class="role-bg bg-#f5f5f5 px-5 py-1 rounded mr-2 cursor-pointer"
        :class="clbRole == item?.id ? 'active' : ''" @click="changeRole(item)">{{ item?.name }}</span>
      <div class="absolute right-16px cursor-pointer" @click="isFold = !isFold">
        <img src="../../../assets/images/more.png" alt="" width="14" />
      </div>
    </div>
    <div class="card-body p-12px flex" v-loading="loading" v-if="isFold" :style="{
      height: topFold ? 'calc(100vh - 188px)' : 'calc(100vh - 302px)',
    }">
      <div class="card-body-tree w-260px">
        <div class="flex items-center mx-4px" style="font-size: 14px; padding: 8px; box-sizing: border-box">
          <img src="../../../assets/images/数据库_data.png" alt="" width="16" /><span class="ml-5px">使用数据库:</span>
        </div>

        <div class="w-93% h-1px bg-#f5f5f5 my-12px"></div>
        <div class="w-93% hid-scroll overflow-y-scroll" style="height: calc(100% - 44px)"
          v-if="childData && childData.length > 0">
          <el-tree :data="childData" :props="defaultProps" node-key="label" :render-content="renderContent"/>
        </div>
        <div v-else class="p-8px text-center" style="font-size: 12px">
          暂无数据
        </div>
      </div>
      <div class="card-body-editor px-16px py-8px overflow-y-auto w-100%" style="height: calc(100% - 16px)"
        ref="scrollContainer">
        <!-- 结论区域特殊处理 - 结论角色(id=4) -->
        <template v-if="clbRole == 4">
          <!-- 显示结论布局切换按钮 -->
          <div class="conclusion-controls">
            <button class="layout-toggle" @click="toggleConclusionLayout">
              {{ conclusionLayout === 'compact' ? '切换为大图模式' : '切换为紧凑模式' }}
            </button>
          </div>

          <!-- 如果当前会话有结论数据，显示所有结论 -->
          <template v-if="editorPromptValue && editorPromptValue.length > 0">
            <!-- 获取当前会话中所有结论数据（id=4的消息） -->
            <div v-for="(conclusion, idx) in getConclusionsInCurrentSession()" :key="conclusion.id"
              class="conclusion-item">
              <!-- 如果结论包含有效的base64图片，则使用图片+说明的布局 -->
              <div v-if="conclusion.hasBase64 && conclusion.base64Src && conclusion.base64Src.length > 100"
                :class="['conclusion-container', conclusionLayout === 'expanded' ? 'expanded-layout' : '']">
                <div class="conclusion-image">
                  <img :src="conclusion.base64Src" alt="结论图表" class="base64-image" @error="handleImageError" />
                </div>
                <div class="conclusion-text markdown-content" v-html="conclusion.markdown"></div>
              </div>
              <!-- 如果结论不包含有效的base64图片，但包含解释内容，则显示解释内容 -->
              <div v-else-if="conclusion.explanation" class="markdown-content full-width-content"
                v-html="conclusion.markdown"></div>
              <!-- 如果既没有base64图片也没有解释内容，则显示原始内容 -->
              <div v-else class="markdown-content full-width-content"
                v-html="conclusion.markdown || processMarkdown(conclusion.rawAnswer || '')"></div>

              <!-- 在多个结论之间添加分隔线 -->
              <div v-if="idx < getConclusionsInCurrentSession().length - 1" class="conclusion-divider"></div>
            </div>
          </template>
        </template>

        <!-- 其他角色的普通内容显示 -->
        <div v-else v-if="editorPromptValue && editorPromptValue.length > 0" v-html="editorValue"
          style="font-size: 14px" class="markdown-content"></div>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.card-container {
  width: 99.8%;
  border: 1px solid #f5f5f5;

  .card-top {
    font-size: 12px;
    padding: 8px;
    box-sizing: border-box;
    background: #f0f0f0;

    .active {
      background: #d4edfb;
    }

    .role-bg:hover {
      background: #d4edfb;
    }
  }

  .card-body {
    width: calc(100% - 20px);

    .card-body-tree {
      height: 100%;
      border-right: 1px solid #f5f5f5;

      .hid-scroll {
        -ms-overflow-style: none;
        scrollbar-width: none;
      }
    }

    .card-body-editor {

      /* 定义滚动条的宽度和背景颜色 */
      ::-webkit-scrollbar {
        width: 16px;
        height: 16px;
        background-color: #f5f5f5;
      }

      /* 定义滚动条轨道的样式 */
      ::-webkit-scrollbar-track {
        -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
        border-radius: 10px;
        background-color: #f5f5f5;
      }

      /* 定义滚动条滑块的样式 */
      ::-webkit-scrollbar-thumb {
        border-radius: 10px;
        -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
        background-color: #555;
      }

      /* 结论区域样式 */
      .conclusion-item {
        margin-bottom: 20px;
        padding-bottom: 20px;
      }

      .conclusion-controls {
        display: flex;
        justify-content: flex-end;
        margin-bottom: 16px;
      }

      .layout-toggle {
        background-color: #f3f4f6;
        border: none;
        border-radius: 4px;
        padding: 6px 12px;
        font-size: 12px;
        color: #374151;
        cursor: pointer;
        transition: all 0.2s;
      }

      .layout-toggle:hover {
        background-color: #e5e7eb;
        color: #111827;
      }

      .conclusion-divider {
        height: 1px;
        background-color: #e9e9e9;
        margin: 20px 0;
      }

      .conclusion-container {
        display: flex;
        flex-direction: column;
        min-height: 200px;
        gap: 20px;

        @media (min-width: 768px) {
          flex-direction: row;
        }

        &.expanded-layout {
          flex-direction: column;

          .conclusion-image {
            width: 100%;
            height: 400px;
            max-height: none;
          }

          .conclusion-text {
            max-height: none;
          }
        }

        .conclusion-image {
          flex: 0 0 auto;
          width: 100%;
          height: 280px;
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: #f9f9f9;
          border-radius: 8px;
          padding: 10px;
          box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.05);

          @media (min-width: 768px) {
            width: 45%;
            height: auto;
            max-height: 350px;
          }

          .base64-image {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
            border-radius: 4px;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
          }

          .image-error {
            max-width: 64px;
            max-height: 64px;
            opacity: 0.5;
          }
        }

        .conclusion-text {
          flex: 1;
          overflow-y: auto;
          max-height: 500px;
          padding: 16px;
          background-color: #fafafa;
          border-radius: 8px;
          box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);

          @media (min-width: 768px) {
            max-height: 350px;
          }
        }
      }
    }
  }
}

/* 添加 Markdown 样式 */
:deep(.markdown-content) {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial,
    sans-serif;
  line-height: 1.6;
  word-wrap: break-word;

  h1,
  h2,
  h3,
  h4,
  h5,
  h6 {
    margin-top: 24px;
    margin-bottom: 16px;
    font-weight: 600;
    line-height: 1.25;
  }

  h1 {
    font-size: 2em;
    border-bottom: 1px solid #eaecef;
    padding-bottom: 0.3em;
  }

  h2 {
    font-size: 1.5em;
    border-bottom: 1px solid #eaecef;
    padding-bottom: 0.3em;
  }

  h3 {
    font-size: 1.25em;
  }

  p,
  blockquote,
  ul,
  ol,
  dl,
  table,
  pre {
    margin-top: 0;
    margin-bottom: 16px;
  }

  code {
    padding: 0.2em 0.4em;
    margin: 0;
    font-size: 85%;
    background-color: rgba(27, 31, 35, 0.05);
    border-radius: 3px;
  }

  pre {
    padding: 16px;
    overflow: auto;
    font-size: 85%;
    line-height: 1.45;
    background-color: #f6f8fa;
    border-radius: 3px;
  }

  pre code {
    padding: 0;
    margin: 0;
    font-size: 100%;
    background-color: transparent;
  }

  blockquote {
    padding: 0 1em;
    color: #6a737d;
    border-left: 0.25em solid #dfe2e5;
  }

  table {
    border-spacing: 0;
    border-collapse: collapse;
    width: 100%;
    overflow: auto;
  }

  table th,
  table td {
    padding: 6px 13px;
    border: 1px solid #dfe2e5;
  }

  table tr {
    background-color: #fff;
    border-top: 1px solid #c6cbd1;
  }

  table tr:nth-child(2n) {
    background-color: #f6f8fa;
  }

  .language-mermaid {
    text-align: center;
  }
}

/* 添加Mermaid相关样式 */
:deep(.mermaid-container) {
  margin: 20px 0;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 6px;
  overflow: auto;
  text-align: center;
}

:deep(.mermaid-error) {
  padding: 10px;
  margin: 10px 0;
  background-color: #fff0f0;
  border-left: 3px solid #ff5252;
  color: #d32f2f;

  pre {
    margin-top: 8px;
    padding: 8px;
    background-color: #ffebee;
    border-radius: 4px;
    overflow: auto;
    font-size: 12px;
  }
}

/* 确保SVG图表正确显示 */
:deep(svg) {
  max-width: 100%;
  height: auto !important;
}

/* Markdown样式中添加对mermaid的支持 */
:deep(.markdown-content) {
  // ... 现有样式保持不变 ...

  .language-mermaid {
    text-align: center;
    background: transparent;
    padding: 0;

    svg {
      margin: 0 auto;
    }
  }
}

/* 在style部分添加以下样式 */
:deep(.mermaid) {
  overflow-x: auto;
  min-height: 100px;
  margin: 20px 0;
  text-align: center;
}

:deep(.mermaid svg) {
  max-width: 100%;
  height: auto !important;
  min-width: 500px;
  /* 确保复杂图表有足够宽度 */
}

/* 针对序列图的特殊样式 */
:deep(.mermaid .actor) {
  fill: #e8e8e8 !important;
  stroke: #c8c8c8 !important;
}

:deep(.mermaid .messageText) {
  fill: #333 !important;
  stroke: none !important;
}

:deep(.mermaid .note) {
  fill: #fff5ad !important;
  stroke: #d9d980 !important;
}

:deep(.mermaid .labelBox) {
  fill: #f4f4f4 !important;
  stroke: #666 !important;
}

/* 针对box分组的样式 */
:deep(.mermaid .labelBox.cluster) {
  fill: rgba(240, 240, 240, 0.5) !important;
  stroke: #ddd !important;
  stroke-dasharray: 3 !important;
}

/* 添加全宽内容样式 */
.full-width-content {
  width: 100%;
  padding: 20px;
  background-color: #fafafa;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}
</style>
